//
//  RegisterViewModel.swift
//  RxStudy
//
//  Created by TRS-Mobile on 2024/6/6.
//  Copyright © 2024 season. All rights reserved.
//

import Foundation
import RxCocoa


struct RegisterViewModel: ViewModelType {
    struct Input {
        let name: Driver<String>
        let pwd: Driver<String>
        let rePwd: Driver<String>
        let registerTrigger: Driver<Void>
    }
    
    struct Output {
        let pwdEnabled: Driver<Bool>
        let rePwdEnabled: Driver<Bool>
        let registerEnabled: Driver<Bool>
        let registerSucess: Driver<Bool>
    }
    
    let netProvider: UserAccountService
    init(netProvider: UserAccountService) {
        self.netProvider = netProvider
    }
    
    func transform(input: Input) -> Output {
        
        let pwdE = input.name
            .map { isMobileNumber($0) }
        
        let isValid = input.pwd
            .map { isValidPassword($0) }
        
        let rePwd = Driver.combineLatest(pwdE, isValid) {
            $0 && $1
        }
        
        let pwdIsValid = Driver.combineLatest(input.pwd, input.rePwd) {
            isValidPassword($0) &&
            isValidPassword($1) &&
            $0 == $1
        }
        
        let rE = Driver.combineLatest(pwdE, pwdIsValid) {
            $0 && $1
        }
        
        let info = Driver.combineLatest(input.name, input.pwd, input.rePwd)
        
        let rs = input.registerTrigger
            .withLatestFrom(info)
            .flatMapLatest { (name, pwd, repwd) in
                netProvider
                    .register(name: name, pwd: pwd, repwd: repwd)
                    .asDriver(onErrorJustReturn: false)
            }
        
        return Output(pwdEnabled: pwdE, 
                      rePwdEnabled: isValid,
                      registerEnabled: rE,
                      registerSucess: rs)
    }
}
